import {Button, message, Select, Input, Tag, TreeSelect, Cascader} from 'antd'
import React, {memo, useState, useEffect, useRef} from 'react'
import {history, connect} from 'umi'

// 可编辑表格
import type {
	ActionType,
	EditableFormInstance,
	ProColumns,
} from '@ant-design/pro-components'
import {EditableProTable} from '@ant-design/pro-components'
import {getEditTableSelect, translateDataToTree} from '@/utils/common/index'

import styles from './index.less'
import {getProcessAuditList, getProcessUpdate} from '@/service/workflow/manage'
import {getAllUserList, getUseList} from '@/service/system/user'
import {getCompany} from '@/service/system/company'
import {getAllCitys} from '@/service/common/index'
import {processConfigType} from '../../dict'

type DataSourceType = {
	itemName: string
	id: React.Key
	labels?: {
		key: string
		label: string
	}[]
	state?: string
	children?: DataSourceType[]
}

const add = memo((props: {user: {orgId: string | number}; location: any}) => {
	const {orgId} = props.user
	// 公司
	const [orginOrgList, setOrginOrgList] = useState<any>([])
	const [orgList, setOrgList] = useState<any>([])
	// 城市
	const [citysList, setCitysList] = useState<any>([])

	// 可编辑表格
	const actionRef = useRef<ActionType>()
	const editorFormRef = useRef<EditableFormInstance<DataSourceType>>()
	const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])
	const [costitemList, setCostitemList] = useState<readonly DataSourceType[]>(
		[],
	)
	const [userList, setUser] = useState<any[]>([])

	// 获取用户数据
	const getUser = () => {
		getAllUserList({}).then((res: any) => {
			if (res?.success) {
				setUser(() =>
					res.data?.map((item: any) => ({
						id: item.id?.toString(),
						name: `${item?.name}（${item?.phone}）`,
					})),
				)
			}
		})
	}

	// 初始化-需求公司数据
	const getOrgFun = () => {
		getCompany({merchantId: orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setOrginOrgList(() => res.data)
				setOrgList(() => list as any)
			}
		})
	}

	// 初始化-城市
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res?.data)
			}
		})
	}

	useEffect(() => {
		getUser()
		getOrgFun()
		getCitysFun()
	}, [orgId])

	// 初始化-列表
	const getList = () => {
		const {key} = props.location.query
		getProcessAuditList({processKey: key}).then((res: any) => {
			if (res?.success) {
				const list = res?.data?.map((item: any) => {
					const newItem = item
					const l = newItem?.processConfigValue
						?.split(',')
						?.filter((s: any) => s && s.trim())
					newItem.processConfigValue = l?.length > 0 ? l : []
					return newItem
				})
				setCostitemList(() => [...list])
			}
		})
	}

	// 根据路由判断当前页面状态
	useEffect(() => {
		getList()
	}, [])

	const submit = () => {
		const arr = costitemList?.filter(
			(item: any) =>
				item?.processConfigValue !== '' && !item?.processConfigValue,
		)
		if (arr?.length > 0) {
			message.error('参数值不能为空')
		} else {
			const list = costitemList.map((item: any) => {
				const newItem = item
				if (Array.isArray(item?.processConfigValue)) {
					newItem.processConfigValue =
						newItem?.processConfigValue.join(',')
				}
				return newItem
			})
			// 立项明细处理
			getProcessUpdate(list)
				.then((res: any) => {
					if (res?.success) {
						message.success(res?.msg)
						history.goBack()
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}
	}

	// 可编辑表格
	const proColumns: ProColumns<DataSourceType>[] = [
		{
			title: '序号',
			dataIndex: 'index',
			valueType: 'index',
			width: 80,
			align: 'center',
			editable: false,
		},
		{
			title: '流程分类Value',
			dataIndex: 'processValue',
			align: 'center',
			editable: false,
			width: 150,
		},
		{
			title: '参数类型',
			dataIndex: 'processConfigType',
			valueType: 'select',
			align: 'center',
			editable: false,
			valueEnum: getEditTableSelect(processConfigType),
			width: 150,
		},
		{
			title: '参数KEY',
			dataIndex: 'processConfigKey',
			editable: false,
			align: 'center',
			width: 150,
		},
		{
			title: '审核节点',
			dataIndex: 'auditNode',
			editable: false,
			align: 'center',
			width: 150,
		},
		{
			title: '参数名称',
			dataIndex: 'processConfigName',
			editable: false,
			align: 'center',
			width: 150,
		},
		{
			title: (
				<>
					<span className="required">* </span> 参数值
				</>
			),
			dataIndex: 'processConfigValue',
			width: 400,
			align: 'center',
			renderFormItem: (schema: any, config: any) => {
				if (config?.record?.processConfigType === 1) {
					const id = Number(config?.record?.processConfigValue[0])
					return orgList?.length > 0 ? (
						<TreeSelect
							showSearch
							treeNodeFilterProp="name"
							style={{width: '100%'}}
							placeholder="请选择"
							fieldNames={{
								label: 'name',
								value: 'id',
							}}
							treeDefaultExpandAll
							treeData={orgList}
							defaultValue={id}
							labelInValue
						/>
					) : null
				}
				if (config?.record?.processConfigType === 2) {
					return orgList?.length > 0 ? (
						<Cascader
							fieldNames={{
								label: 'name',
								value: 'id',
								children: 'cityInfoList',
							}}
							options={citysList}
							placeholder="请选择"
						/>
					) : null
				}
				if (config?.record?.processConfigType === 3) {
					return <Input placeholder="请输入" />
				}
				if (config?.record?.processConfigType === 4) {
					const id = Number(config?.record?.processConfigValue[0])
					return userList?.length > 0 ? (
						<Select
							showSearch
							filterOption={(input, option) =>
								(option?.name ?? '').includes(input)
							}
							placeholder="请选择"
							fieldNames={{
								value: 'id',
								label: 'name',
							}}
							options={[...userList]}
							defaultValue={id}
							labelInValue
						/>
					) : null
				}
				if (config?.record?.processConfigType === 5) {
					return <Input placeholder="请输入" />
				}
				if (config?.record?.processConfigType === 6) {
					return <Input placeholder="请输入" />
				}
				if (config?.record?.processConfigType === 7) {
					return (
						<Select
							showSearch
							filterOption={(input, option) =>
								(option?.name ?? '').includes(input)
							}
							placeholder="请选择"
							mode="multiple"
							fieldNames={{
								value: 'id',
								label: 'name',
							}}
							options={[...userList]}
						/>
					)
				}
				return <Input placeholder="请输入" />
			},
			render: (text: any, row: any) => {
				if (row?.processConfigType === 1) {
					const list = orginOrgList?.filter(
						(item: any) =>
							row?.processConfigValue[0]?.toString() ===
							item?.id?.toString(),
					)
					return list?.map((item: any) => (
						<Tag color="processing" key={item.id}>
							{item.name}
						</Tag>
					))
				}
				if (row?.processConfigType === 2) {
					const list = citysList?.filter(
						(item: any) =>
							row?.processConfigValue[0]?.toString() ===
							item?.id?.toString(),
					)[0]
					const city = list?.cityInfoList?.filter(
						(item: any) =>
							row?.processConfigValue[1]?.toString() ===
							item?.id?.toString(),
					)[0]
					const name = `${list?.name} / ${city?.name}`
					return list ? <Tag color="processing">{name}</Tag> : null
				}
				if (row?.processConfigType === 4) {
					const list = userList.filter(
						(item: {id: string; name: string}) =>
							row?.processConfigValue?.includes(
								item?.id?.toString(),
							),
					)
					return list ? (
						<Tag color="processing">{list[0]?.name}</Tag>
					) : null
				}
				if (row?.processConfigType === 7) {
					const list = userList?.filter((item: any) =>
						row?.processConfigValue?.includes(item?.id?.toString()),
					)
					return list?.map((item: any) => (
						<Tag color="processing" key={item.id}>
							{item.name}
						</Tag>
					))
				}
				if (row?.processConfigType === 6) {
					return row?.processConfigValue
				}
				return ''
			},
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '操作',
			valueType: 'option',
			fixed: 'right',
			width: 200,
			render: (text, record: any, _, action) => [
				<Button
					type="link"
					key="editable"
					size="small"
					onClick={() => {
						action?.startEditable?.(record.id)
					}}>
					编辑
				</Button>,
			],
		},
	]
	// 获取动态表格数据
	const setCostitem = (key: any, row: any) => {
		if (row?.processConfigType === 7) {
			const list = costitemList.map((t) =>
				t.id === key
					? {
							...row,
							processConfigValue: row?.processConfigValue?.map(
								(i: any) => i.toString(),
							),
					  }
					: t,
			)
			setCostitemList(() => list)
		} else if (row?.processConfigType === 4) {
			const list = costitemList.map((t) =>
				t.id === key
					? {
							...row,
							processConfigValue:
								Object.prototype.toString.call(
									row?.processConfigValue,
								) === '[object Array]'
									? row?.processConfigValue
									: [row?.processConfigValue?.value],
					  }
					: t,
			)
			setCostitemList(() => list)
		} else if (row?.processConfigType === 6) {
			const list = costitemList.map((t) =>
				t.id === key
					? {
							...row,
							processConfigValue: row?.processConfigValue,
					  }
					: t,
			)
			setCostitemList(() => list)
		} else if (row?.processConfigType === 1) {
			const list = costitemList.map((t) =>
				t.id === key
					? {
							...row,
							processConfigValue: [
								row?.processConfigValue?.value,
							],
					  }
					: t,
			)
			setCostitemList(() => list)
		} else if (row?.processConfigType === 2) {
			const list = costitemList.map((t) =>
				t.id === key
					? {
							...row,
							processConfigValue: row?.processConfigValue
								? row?.processConfigValue
								: [],
					  }
					: t,
			)
			setCostitemList(() => list)
		}
	}
	return (
		<div className={styles.admittanceAdd}>
			<div className={`${styles.content} ${styles.formDetils}`}>
				<EditableProTable<DataSourceType>
					bordered
					rowKey="id"
					key="id"
					actionRef={actionRef}
					scroll={{
						x: '100%',
					}}
					editableFormRef={editorFormRef}
					maxLength={5}
					recordCreatorProps={false}
					columns={proColumns}
					value={costitemList}
					editable={{
						editableKeys,
						onSave: async (key: any, row: any) =>
							setCostitem(key, row),
						onChange: setEditableRowKeys,
						actionRender: (row, config, dom) => [
							dom.save,
							dom.cancel,
						],
					}}
				/>
				<div className={styles.wrap}>
					<Button
						onClick={() => {
							history.go(-1)
						}}>
						取消
					</Button>
					<Button type="primary" htmlType="submit" onClick={submit}>
						保存
					</Button>
				</div>
			</div>
		</div>
	)
})
export default connect(({user}: any) => ({user}))(add)
